import './style.scss'
import '@wangeditor/editor/dist/css/style.css'
import React, {
  useState,
  useEffect,
  useImperativeHandle,
  forwardRef
} from 'react'
import type { CSSProperties } from 'react'
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import type {
  IDomEditor,
  IEditorConfig,
  IToolbarConfig
} from '@wangeditor/editor'

export interface IEditorRef {
  getHtml: () => string
  setHtml: (html: string) => void
  editor: IDomEditor | null
}

interface IProps {
  height?: number
  color?: string
}

const MyEditor = forwardRef<IEditorRef, IProps>(
  ({ height = 500, color = '#ccc' }, _ref) => {
    const [html, setHtml] = useState('')
    // editor 实例
    const [editor, setEditor] = useState<IDomEditor | null>(null)
    // 工具栏配置
    const toolbarConfig: Partial<IToolbarConfig> = {}
    // 编辑器配置
    const editorConfig: Partial<IEditorConfig> = {
      placeholder: '请输入内容...'
    }

    // 对外暴露的方法
    useImperativeHandle(_ref, () => {
      return {
        getHtml: () => html,
        setHtml: (html: string) => setHtml(html),
        editor
      }
    })

    // 及时销毁 editor ，重要！
    useEffect(() => {
      return () => {
        if (editor == null) return
        editor.destroy()
        setEditor(null)
      }
    }, [editor])

    return (
      <>
        <div
          className="my-editor-box"
          style={{ '--editor-color': color } as CSSProperties}
        >
          <Toolbar
            editor={editor}
            defaultConfig={toolbarConfig}
            mode="default"
            className="toolbar"
          />
          <Editor
            defaultConfig={editorConfig}
            value={html}
            onCreated={setEditor}
            onChange={(editor) => setHtml(editor.getHtml())}
            mode="default"
            className="editor"
            style={{ height }}
          />
        </div>
      </>
    )
  }
)

export default MyEditor
